# -*- coding: utf-8 -*-
import quecgnss
import ure as re

def GNSS_Read():
    data = quecgnss.read(1024)
    data_gnss = data[1].decode()
    if len(data_gnss)==0:
        print("None Data")
    else:
        print("Get Data")
        #print(data_gnss)
        data1 = re.search("GNRMC(.+?)M", data_gnss)
        deta2 = re.search("GPGSV(.+?)M", data_gnss)
        deta3 = re.search("BDGSV(.+?)M", data_gnss)
        data4 = re.search("GNGGA(.+?)M", data_gnss)
        try:
            if data1.group(0).split(",")[2] == 'A': 
                print("Available Data")           
                li=[data4.group(0).split(",")[2],data4.group(0).split(",")[3],data4.group(0).split(",")[4],data4.group(0).split(",")[5]]
                print(li)
                lat0=int(int(float(li[0]))/100)
                lat1=int(int(float(li[0]))%100)
                lat2=int(li[0].split(".")[1])
                lon0=int(int(float(li[2]))/100)
                lon1=int(int(float(li[2]))%100)
                lon2=int(li[2].split(".")[1])
                lat_d=str(lat0)
                lat_m=str(lat1)+"."+str(lat2)
                lon_d=str(lon0)
                lon_m=str(lon1)+"."+str(lon2)

                lat=float(lat_m)/60+float(lat_d)
                lon=float(lon_m)/60+float(lon_d)

                return lon,lat
        except Exception as e:
            print("GNSS Error",e)
            pass
    return None

def GNSS_Init():
    ret = quecgnss.init()
    if ret == 0:
        print('GNSS init ok.')
    else:
        print('GNSS init failed.')
        return -1
    ret = quecgnss.get_state()
    if ret == 2:
        return 1
    else:
        return 0

